//
//  YBHealthControllerNew.m
//  孕妙
//
//  Created by Raoy on 16/4/7.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "YBHealthControllerNew.h"
#import "YBCalenderButton.h"
#import "YBParameterListView.h"
#import "AppDelegate.h"
//日历
#import "YBHealthCalendar.h"
#import "YBHealthParmater.h"
#import "AFNetworking.h"
#import "MJExtension.h"
#import "passValue.h"
//#import "foodPassValue.h"
#import "YBHealthTableViewCell.h"
#import "TestItemManagerController.h"
#import "YBStartRecordController.h"
//趋势图
#import "YBWeightDataController.h"
#import "YBXueyaDataController.h"
#import "YBXueTangDataController.h"
#import "YBHeartDataController.h"
#import "YBTaiHeartDataController.h"
#import "YBTiWenDataController.h"

#import "YBBMIDataController.h"
#import "YBFatDataController.h"
#import "YBNeiZangViewController.h"
#import "YBWaterPercentViewController.h"
#import "YBMuscleViewController.h"
#import "YBBoneViewController.h"
#import "YBNengLiangViewController.h"

#define cellHeight (30 * (DeviceHeight / 480))

@interface YBHealthControllerNew ()<UITableViewDelegate, UITableViewDataSource>

/**
 * 圆盘View
 */
@property (nonatomic, strong) UIView *diskView;
/**
 * 孕期lable
 */
@property (nonatomic, strong) UILabel *yunqiL;
/**
 * 离孕产期天数
 */
@property (nonatomic, strong) UILabel *dayCountL;
/**
 * 建议View
 */
@property (nonatomic, strong) UIView *adviceView;
/**
 * 参数
 */
@property (nonatomic, strong) UIView *paramterView;
/**
 * 建议
 */
@property (nonatomic, strong) UITextView *adviceText;
/**
 * 日历
 */
@property (nonatomic, strong) YBHealthCalendar *healthCalendar;
/**
 日历是否正在动画
 */
@property (assign, getter = isAnimating) BOOL animating;
/**
 * 灰色背景View
 */
@property (nonatomic, weak) UIView *shadowView;
/**
 当前日历上显示数据的日期，界面上当前显示的日期
 */
@property (nonatomic, strong) NSDate *calendarDisplayDate;
/**
 * 获得当天数据的数组
 */
@property (nonatomic, strong) NSArray *theDayArray;

/**
 * 最后一次月经的时间
 */
@property (nonatomic, assign) long long lastYuejingTime;
//体重，体温，血压等表视图
@property (nonatomic, strong) UITableView *HealthTableView;
//开始记录Button
@property (strong, nonatomic) UIButton  *startBtn;
//设备管理Button
@property (strong, nonatomic)UIButton *deviceManbtn;
//展示的设备名
@property(copy, nonatomic)NSMutableArray *itemNameArray;
//选中设备
@property(copy, nonatomic)NSString *selectedStr;

@property(strong, nonatomic)NSMutableArray *itemNameArray2;

@property(strong, nonatomic)NSMutableArray *itemValueArray2;
@end

@implementation YBHealthControllerNew
{
    NSInteger _weightFlag; //判断是否是体成分秤
    NSArray *_unitArray; //体成分单位数组
    NSArray *_tiZhiImageArray; //体成分图片数组
}

- (NSMutableArray *)itemNameArray
{
    if (_itemNameArray == nil) {
        _itemNameArray = [NSMutableArray array];
    }
    return _itemNameArray;
}

- (NSMutableArray *)itemNameArray2
{
    if (_itemNameArray2 == nil) {
        _itemNameArray2 = [NSMutableArray array];
    }
    return _itemNameArray2;
}

- (NSMutableArray *)itemValueArray2
{
    if (_itemValueArray2 == nil)
    {
        _itemValueArray2 = [NSMutableArray array];
    }
    return _itemValueArray2;
}

- (void)setLastYuejingTime:(long long)lastYuejingTime
{
    _lastYuejingTime = lastYuejingTime;
    long long yuchanTime = lastYuejingTime + 280 * (60 * 60 * 24);
    NSDate *tempDate = [NSDate dateWithTimeIntervalSince1970:yuchanTime];
    long long timeCha = [tempDate timeIntervalSince1970] - [[NSDate date] timeIntervalSince1970];
    NSInteger daynum =  (long)timeCha / (60 * 60 * 24);
    self.dayCountL.text = [NSString stringWithFormat:@"%ld", (long)daynum];
}

- (void)setTheDayArray:(NSArray *)theDayArray
{
    _theDayArray = theDayArray;
    // 更新UI
    if (theDayArray.count == 0) {
        SYLog(@"没有数据");
    }
}

- (NSDate *)calendarDisplayDate
{
    if (_calendarDisplayDate == nil) {
        _calendarDisplayDate = [NSDate date];
    }
    return _calendarDisplayDate;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"健康监测";
    self.view.backgroundColor = SYColor(245, 245, 245);
   
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 10, 30, 30);
    [rightBtn setImage:[UIImage imageNamed:@"calendar_icon"] forState:UIControlStateNormal];
    
    [rightBtn addTarget:self action:@selector(clickrightButtonToSupper:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    sleep(0.5);
    //中间圆图
    [self setupDiskView];
    //开始记录
    [self setupStartView];
    
    //监测对象数据列表
    [self setupParameterListTableView];
    
    //设备管理button
    [self setDeviceManagerBtn];
}

- (NSString *)judgeyunqi
{
    NSInteger tempyunqitime = [[[NSUserDefaults standardUserDefaults] objectForKey:@"yunqiValue"] integerValue];
    NSString *tempStr = nil;
    switch (tempyunqitime) {
        case 1:
            tempStr = @"孕早期";
            break;
        case 2:
            tempStr = @"孕中期";
            break;
        case 3:
            tempStr = @"孕晚期";
            break;
            
        default:
            break;
    }
    return tempStr;
}

- (void)setupDiskView
{
    self.diskView = [[UIView alloc] initWithFrame:CGRectMake(0, SYNavigateHeight + (cellHeight / 2), DeviceWidth, LayoutHeight * 0.3564)];
    [self.view addSubview:self.diskView];
    
    CGFloat backViewW = LayoutHeight * 0.3564;
    CGFloat backViewH = LayoutHeight * 0.3564;
    CGFloat backViewX = (DeviceWidth - backViewW) * 0.5;
    CGFloat backViewY = 0;
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(backViewX, backViewY, backViewW, backViewH)];
    //    backView.backgroundColor = [UIColor redColor];ba
    [self.diskView addSubview:backView];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, backViewW, backViewH)];
    imageView.image = [UIImage imageNamed:@"YB_disk"];
    [backView addSubview:imageView];
    
    UILabel *yunqiL = [[UILabel alloc] initWithFrame:CGRectMake(0, backViewH * 0.257, backViewW, backViewH * 0.1714)];
    self.yunqiL = yunqiL;
    NSString *YunqitempStr = [self judgeyunqi];
    yunqiL.text = YunqitempStr;
    yunqiL.textColor = SYColor(224, 93, 167);
    yunqiL.textAlignment = NSTextAlignmentCenter;
    [backView addSubview:yunqiL];
    
    NSString *juliStr = @"距离预产期";
    UILabel *juliL = [[UILabel alloc] init];
    juliL.text = juliStr;
    juliL.textColor = SYColor(83, 83, 83);
    juliL.textAlignment = NSTextAlignmentCenter;
    [backView addSubview:juliL];
    
    UILabel *dayCountL = [[UILabel alloc] init];
    self.dayCountL = dayCountL;
    dayCountL.text = [NSString stringWithFormat:@"%ld", (long)self.dayCountInt];
    dayCountL.textColor = SYColor(224, 93, 167);
    dayCountL.textAlignment = NSTextAlignmentRight;
    [backView addSubview:dayCountL];
    
    UILabel *daytextL = [[UILabel alloc] init];
    daytextL.text = @"天";
    daytextL.textColor = SYColor(224, 93, 167);
    daytextL.textAlignment = NSTextAlignmentLeft;
    [backView addSubview:daytextL];
    NSDictionary * juliAttr = nil;
    CGSize juliLSize;
    if (SYDevice4s) {
        yunqiL.font = [UIFont systemFontOfSize:22];
        juliL.font = [UIFont systemFontOfSize:12];
        juliAttr = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:12.0]};
        juliLSize = [juliStr boundingRectWithSize:CGSizeMake(DeviceWidth, backViewH * 0.1) options:NSStringDrawingUsesLineFragmentOrigin attributes:juliAttr context:nil].size;
        dayCountL.font = [UIFont boldSystemFontOfSize:16];
        daytextL.font = [UIFont boldSystemFontOfSize:12];
    } else if (SYDevice6p) {
        yunqiL.font = [UIFont systemFontOfSize:35];
        juliL.font = [UIFont systemFontOfSize:18];
        juliAttr = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:18.0]};
        juliLSize = [juliStr boundingRectWithSize:CGSizeMake(DeviceWidth, backViewH * 0.1) options:NSStringDrawingUsesLineFragmentOrigin attributes:juliAttr context:nil].size;
        dayCountL.font = [UIFont boldSystemFontOfSize:28];
        daytextL.font = [UIFont boldSystemFontOfSize:18];
    }  else if (SYDevice5) {
        yunqiL.font = [UIFont systemFontOfSize:25];
        juliL.font = [UIFont systemFontOfSize:12];
        juliAttr = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:12.0]};
        juliLSize = [juliStr boundingRectWithSize:CGSizeMake(DeviceWidth, backViewH * 0.1) options:NSStringDrawingUsesLineFragmentOrigin attributes:juliAttr context:nil].size;
        dayCountL.font = [UIFont boldSystemFontOfSize:20];
        daytextL.font = [UIFont boldSystemFontOfSize:14];
    } else if (SYDevice6) {
        yunqiL.font = [UIFont systemFontOfSize:30];
        juliL.font = [UIFont systemFontOfSize:15];
        juliAttr = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:15.0]};
        juliLSize = [juliStr boundingRectWithSize:CGSizeMake(DeviceWidth, backViewH * 0.1) options:NSStringDrawingUsesLineFragmentOrigin attributes:juliAttr context:nil].size;
        dayCountL.font = [UIFont boldSystemFontOfSize:25];
        daytextL.font = [UIFont boldSystemFontOfSize:15];
    }
    
    CGRect juliLFrame = CGRectMake((backViewW - juliLSize.width) * 0.5, backViewH * 0.5285, juliLSize.width + 1, backViewH * 0.1);
    juliL.frame = juliLFrame;
    CGRect dayCountLFrame = CGRectMake(0, backViewH * 0.6428, backViewW * 0.5 + juliLFrame.size.width * 0.20, backViewH * 0.1286);
    self.dayCountL.frame = dayCountLFrame;
    CGRect daytextLFrame = CGRectMake(CGRectGetMaxX(dayCountL.frame) + 3, backViewH * 0.6428, backViewW * 0.5, backViewH * 0.1286);
    daytextL.frame = daytextLFrame;
}

- (void)setupStartView
{
    CGFloat startBtnY = CGRectGetMaxY(self.diskView.frame) ;
    CGFloat startBtnW = 120;
    CGFloat startBtnH = 30;;
    CGFloat startBtnX = (DeviceWidth - startBtnW) * 0.5;
    UIImageView *tempImageView = [[UIImageView alloc] init];
    tempImageView.frame = CGRectMake(DeviceWidth * 0.5 - 56, startBtnY + 3, 120, 24);
    tempImageView.image = [UIImage imageNamed:@"health_pen"];
    [self.view addSubview:tempImageView];
    
    _startBtn = [[UIButton alloc] initWithFrame:CGRectMake(startBtnX, startBtnY, startBtnW, startBtnH)];
//    [_startBtn setBackgroundImage:[UIImage imageNamed:@"health_pen"] forState:UIControlStateNormal];
    [_startBtn setTitleColor:SYColor(232, 106, 165) forState:UIControlStateNormal];
    [_startBtn setTitle:@"开始记录" forState:UIControlStateNormal];
    _startBtn.titleLabel.font = [UIFont systemFontOfSize:20];
    [_startBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [self.view addSubview:_startBtn];
    _startBtn.layer.cornerRadius =  10;
    _startBtn.layer.masksToBounds = YES;
    [_startBtn addTarget:self action:@selector(clickStartJiance:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setupParameterListTableView
{
    _HealthTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.startBtn.frame) + 2, DeviceWidth, cellHeight * 6) style:UITableViewStylePlain];
    _HealthTableView.delegate = self;
    _HealthTableView.dataSource = self;
    _HealthTableView.backgroundColor = SYColor(245, 245, 245);
    [self.view addSubview:self.HealthTableView];
}

- (void)setDeviceManagerBtn
{
    _deviceManbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _deviceManbtn.frame = CGRectMake(0, (CGRectGetMaxY(self.HealthTableView.frame) + DeviceHeight - 40) * 0.5 , DeviceWidth, 40);
//    _deviceManbtn.frame = CGRectMake(0, DeviceHeight - 40, DeviceWidth, 40);
    [_deviceManbtn setTitle:@"设备管理" forState:UIControlStateNormal];
    _deviceManbtn.backgroundColor = SYColor(249, 150, 200);
    [self.view addSubview:self.deviceManbtn];
    
    [_deviceManbtn addTarget:self action:@selector(pushDeviceManager:) forControlEvents:UIControlEventTouchUpInside];
}


- (void)pushDeviceManager:(UIButton *)button
{
    TestItemManagerController *startCtrT = [[TestItemManagerController alloc] init];
    startCtrT.itemNameMgr = self.selectedStr;
    [self.navigationController pushViewController:startCtrT animated:YES];
}

- (void)clickStartJiance:(id)sender
{
    NSLog(@"开始记录");
    YBStartRecordController *startCtr = [[YBStartRecordController alloc] init];
    startCtr.itemLArray = [NSArray arrayWithArray:self.itemNameArray];
    
    [self.navigationController pushViewController:startCtr animated:YES];
}

- (void)clickrightButtonToSupper:(UIButton *)button
{
    if (self.animating) {
        return;
    }
    if (self.shadowView) {
        // 动画消除日历
        [UIView animateWithDuration:0.3 animations:^{
            self.healthCalendar.transform = CGAffineTransformMakeTranslation(0, -350);
            self.animating = YES;
        } completion:^(BOOL finished) {
            [self.healthCalendar removeObserver:self forKeyPath:@"date"];
            [self.healthCalendar removeFromSuperview];
            self.healthCalendar = nil;
            [self.shadowView removeFromSuperview];
            self.shadowView = nil;
            self.animating = NO;
        }];
        
    } else {
        UIView *shadowView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        self.shadowView = shadowView;
        shadowView.backgroundColor = [UIColor grayColor];
        shadowView.alpha = 0.1;
        [self.view addSubview:shadowView];
        
        YBHealthCalendar *healthCalendar = [[YBHealthCalendar alloc] initWithCurrentDate:[NSDate date]];
        self.healthCalendar = healthCalendar;
        CGRect frame = healthCalendar.frame;
        frame.origin.y = -350;
        healthCalendar.frame = frame;
        [self.view addSubview:healthCalendar];
        
        // 监听date属性变化
        [self.healthCalendar addObserver:self forKeyPath:@"date" options:0 context:nil];
        [self observeValueForKeyPath:nil ofObject:nil change:nil context:nil];
        
        // 切换日历选中日期
        [self.healthCalendar setCurrentDate:self.calendarDisplayDate];
        
        [UIView animateWithDuration:0.3 animations:^{
            healthCalendar.transform = CGAffineTransformMakeTranslation(0, 450);
            self.animating = YES;
        } completion:^(BOOL finished) {
            self.animating = NO;
            CGRect frame = healthCalendar.frame;
            frame.origin.y = SYNavigateHeight;
            healthCalendar.frame = frame;
        }];
    }
    
}



- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"date"]) {
        [UIView animateWithDuration:0.3 animations:^{
            self.healthCalendar.transform = CGAffineTransformMakeTranslation(0, -350);
            self.animating = YES;
        } completion:^(BOOL finished) {
            //  移除监听
            [self.healthCalendar removeObserver:self forKeyPath:@"date"];
            [self.healthCalendar removeFromSuperview];
            self.healthCalendar = nil;
            [self.shadowView removeFromSuperview];
            self.shadowView = nil;
            self.animating = NO;
        }];
        self.calendarDisplayDate = self.healthCalendar.date;
        [self getBodyFatData];
        [self getUserParmaterData:[passValue passValue].passValueName username:[passValue passValue].saveDataUserName];
        
    }
    
}

#pragma mark touchesBegan
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.shadowView) {
        [UIView animateWithDuration:0.3 animations:^{
            self.shadowView.alpha = 0.0;
            self.healthCalendar.transform = CGAffineTransformMakeTranslation(0, -350);
            self.animating = YES;
        } completion:^(BOOL finished) {
            [self.healthCalendar removeObserver:self forKeyPath:@"date"];
            [self.healthCalendar removeFromSuperview];
            self.healthCalendar = nil;
            [self.shadowView removeFromSuperview];
            self.shadowView = nil;
            self.animating = NO;
        }];
    }
}



/**
 * 获得手机时间(年月日时分秒)
 */
- (NSDateComponents *)convertFromDateToDateComp:(NSDate *)tempDate
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekday;
    
    // 1.获得当前时间的年月日
    NSDateComponents *nowCmps = [calendar components:unit fromDate:tempDate];
    
    return nowCmps;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.itemNameArray2.count) {
        return self.itemNameArray2.count;
    } else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"healthCellID";
    YBHealthTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"YBHealthTableViewCell" owner:self options:nil]lastObject];
        cell.backgroundColor = SYColor(245, 245, 245);
        
        [cell.HealthLable setTextColor:SYColor(200, 100, 140)];
        
        cell.HealthLable.text = [self.itemNameArray2 objectAtIndex:indexPath.row];
        YBHealthParmater *tempParmater = self.theDayArray.firstObject;
        
        if (self.selectedStr) {
            if ([cell.HealthLable.text isEqualToString:@"体重"]) {
                _weightFlag = 1;
                cell.Healthimage.image = [UIImage imageNamed:@"health_weight"];
                cell.HealthValueLabel.text = [NSString stringWithFormat:@"%.1f kg", tempParmater.weight];
            }else if ([cell.HealthLable.text isEqualToString:@"体温"]){
                cell.Healthimage.image = [UIImage imageNamed:@"health_temperature"];
                cell.HealthValueLabel.text = [NSString stringWithFormat:@"%.1f °C", tempParmater.tem];
            }else if ([cell.HealthLable.text isEqualToString:@"血糖"]){
                cell.Healthimage.image = [UIImage imageNamed:@"health_bloodsugar"];
                cell.HealthValueLabel.text = [NSString stringWithFormat:@"%.1f mmol/L", tempParmater.bloodG];
                
            }else if ([cell.HealthLable.text isEqualToString:@"血压"]){
                cell.Healthimage.image = [UIImage imageNamed:@"health_mmHg"];
                cell.HealthValueLabel.text = [NSString stringWithFormat:@"高：%ld  低：%ld", (long)tempParmater.dbp, (long)tempParmater.sbp];
                
            }else if ([cell.HealthLable.text isEqualToString:@"胎心"]){
                cell.Healthimage.image = [UIImage imageNamed:@"health_FHR"];
//                cell.HealthValueLabel.text = @"暂时没有";
            }else if ([cell.HealthLable.text isEqualToString:@"心率"]){
                cell.Healthimage.image = [UIImage imageNamed:@"health_bpm"];
                cell.HealthValueLabel.text = [NSString stringWithFormat:@"%ld 次/min", (long)tempParmater.heartRate];
            }else if (_weightFlag == 1) {
                cell.Healthimage.image = [UIImage imageNamed:_tiZhiImageArray[indexPath.row - 1]];
                if ([self.itemValueArray2 firstObject]) {
                    cell.HealthValueLabel.text = [NSString stringWithFormat:@"%.1f %@", [[self.itemValueArray2 objectAtIndex:indexPath.row - 1]floatValue], _unitArray[indexPath.row - 1]];
                }else{
                    cell.HealthValueLabel.text = [NSString stringWithFormat:@"0%@", _unitArray[indexPath.row - 1]];
                }
            }
        }
    }
    
       return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YBHealthParmater *tempParmater = self.theDayArray.firstObject;
    if (_weightFlag == 1) {
        switch (indexPath.row) {
            case 1:
            {
                YBBMIDataController *bmiVC = [[YBBMIDataController alloc] init];
                bmiVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:bmiVC animated:YES];
            }
                break;
            case 2:
            {
                YBFatDataController *bmiVC = [[YBFatDataController alloc] init];
                bmiVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:bmiVC animated:YES];
            }
                break;
            case 3:
            {
                YBNeiZangViewController *bmiVC = [[YBNeiZangViewController alloc] init];
                bmiVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:bmiVC animated:YES];
            }
                break;
            case 4:
            {
                YBWaterPercentViewController *bmiVC = [[YBWaterPercentViewController alloc] init];
                bmiVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:bmiVC animated:YES];
            }
                break;
            case 5:
            {
                YBMuscleViewController *bmiVC = [[YBMuscleViewController alloc] init];
                bmiVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:bmiVC animated:YES];
            }
                break;
            case 6:
            {
                YBBoneViewController *bmiVC = [[YBBoneViewController alloc] init];
                bmiVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:bmiVC animated:YES];
            }
                break;
            case 7:
            {
                YBNengLiangViewController *bmiVC = [[YBNengLiangViewController alloc] init];
                bmiVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:bmiVC animated:YES];
            }
                break;
                
            default:
                break;
        }
    }
    
    
    
    if ([[self.itemNameArray2 objectAtIndex:indexPath.row] isEqualToString:@"体重"]) {
        YBWeightDataController *weightVC = [[YBWeightDataController alloc] init];
        weightVC.hidesBottomBarWhenPushed = YES;
        weightVC.itemIntvalue3 = tempParmater.weight;
        [self.navigationController pushViewController:weightVC animated:YES];
      
        return;
    }
    
    if ([[self.itemNameArray2 objectAtIndex:indexPath.row] isEqualToString:@"体温"]) {
        YBTiWenDataController *tiwenVC = [[YBTiWenDataController alloc] init];
        tiwenVC.hidesBottomBarWhenPushed = YES;
        tiwenVC.itemIntvalue3 = tempParmater.tem;
        [self.navigationController pushViewController:tiwenVC animated:YES];
        
        return;
    }
    
    if ([[self.itemNameArray2 objectAtIndex:indexPath.row] isEqualToString:@"血压"]) {
        YBXueyaDataController *xueyaVC = [[YBXueyaDataController alloc] init];
        xueyaVC.hidesBottomBarWhenPushed = YES;
        xueyaVC.itemIntvalue1 = (long)tempParmater.dbp;
        xueyaVC.itemIntvalue2 = (long)tempParmater.sbp;
        [self.navigationController pushViewController:xueyaVC animated:YES];
        return;
    }
    
    if ([[self.itemNameArray2 objectAtIndex:indexPath.row] isEqualToString:@"血糖"]) {
        YBXueTangDataController *xuetangVC = [[YBXueTangDataController alloc] init];
        xuetangVC.hidesBottomBarWhenPushed = YES;
        xuetangVC.itemIntvalue3 = tempParmater.bloodG;
        [self.navigationController pushViewController:xuetangVC animated:YES];
        return;
    }
    
    if ([[self.itemNameArray2 objectAtIndex:indexPath.row] isEqualToString:@"心率"]) {
        YBHeartDataController *heartVC = [[YBHeartDataController alloc] init];
        heartVC.hidesBottomBarWhenPushed = YES;
        heartVC.itemIntvalue1 = (long)tempParmater.heartRate;
        [self.navigationController pushViewController:heartVC animated:YES];
        return;
    }
    
//    if ([[self.itemNameArray objectAtIndex:indexPath.row] isEqualToString:@"胎心"]) {
//        YBTaiHeartDataController *taiHeratVC = [[YBTaiHeartDataController alloc] init];
//        taiHeratVC.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:taiHeratVC animated:YES];
//        return;
//    }
}

/**
 * 请求监测数据
 */
- (void)getUserParmaterData:(NSString *)account username:(NSString *)username
{
    // 1.创建请求管理对象
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    // 2.封装请求参数
    NSDateComponents *tempComp  = [self convertFromDateToDateComp:self.calendarDisplayDate];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"account"] = account;
    params[@"username"] = username;
    params[@"devicename"] = @"phealth";
    params[@"date"] = [NSString stringWithFormat:@"%ld%02ld%02ld000000", (long)tempComp.year, (long)tempComp.month, (long)tempComp.day];
    SYLog(@"++++_+_+_%@", [NSString stringWithFormat:@"%ld%02ld%02ld000000", (long)tempComp.year, (long)tempComp.month, (long)tempComp.day]);
    // 3.发送请求
    [mgr GET:URL_Health_baby_getDevUseInfo parameters:params
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         NSLog(@"responseObject:%@", responseObject);
         if (responseObject[@"response"]) {
             // 取出data字典数组
             NSArray *dataDictArray = responseObject[@"data"];
             self.theDayArray = [YBHealthParmater mj_objectArrayWithKeyValuesArray:dataDictArray];
             [self.HealthTableView reloadData];

         } else {
             [MBProgressHUD showError:@"请求数据失败,请检查网络"];
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [MBProgressHUD showError:@"请求数据失败,请检查网络"];
     }];
}

//请求体脂数据
- (void)getBodyFatData
{
    
    
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[passValue passValue].passValueName forKey:@"account"];
    [params setObject:[passValue passValue].saveDataUserName forKey:@"username"];
    
    NSDateComponents *tempComp  = [self convertFromDateToDateComp:self.calendarDisplayDate];
    params[@"date"] = [NSString stringWithFormat:@"%ld%02ld%02ld000000", (long)tempComp.year, (long)tempComp.month, (long)tempComp.day];
    params[@"date1"] = [NSString stringWithFormat:@"%ld%02ld%02ld000000", (long)tempComp.year, (long)tempComp.month, (long)tempComp.day + 1];
    
    params[@"devicename"] = @"zfc";
    [mgr GET: URL_Health_baby_getDevUseInfo parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSLog(@"responseObject:%@", responseObject);
        if ([responseObject objectForKey:@"response"]) {
            if ([[responseObject objectForKey:@"data"] firstObject]) {
                
            
            NSMutableDictionary *tempdic = [[responseObject objectForKey:@"data"] firstObject];
            [_itemValueArray2 addObject:[NSString stringWithFormat:@"%.1f", [[tempdic objectForKey:@"bmi"] floatValue]]];
            [_itemValueArray2 addObject: [NSString stringWithFormat:@"%.1f", [[tempdic objectForKey:@"fat"] floatValue]]];
            [_itemValueArray2 addObject:[tempdic objectForKey:@"viscerafat"]];
            [_itemValueArray2 addObject:[tempdic objectForKey:@"water"]];
            float tempmuscle = [[tempdic objectForKey:@"muscle"] floatValue]*0.01*[[tempdic objectForKey:@"weight"] floatValue];
            [_itemValueArray2 addObject:[NSString stringWithFormat:@"%.1f", tempmuscle]];
            [_itemValueArray2 addObject:[tempdic objectForKey:@"bone"]];
            [_itemValueArray2 addObject:[tempdic objectForKey:@"kcal"]];
            
            }else{
                _itemValueArray2 = nil;
            }
            
            [self.HealthTableView reloadData];
            
        }else{
            [MBProgressHUD showError:[NSString stringWithFormat:@"%@", [responseObject objectForKey:@"message"] ]];
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD showError:@"请求数据失败,请检查网络"];
    }];
}

//请求设备选择数据
- (void)getHealthNumberOfTests
{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[passValue passValue].passValueName forKey:@"account"];
    [params setObject:[passValue passValue].saveDataUserName forKey:@"username"];
    
    
    [mgr GET:URL_Health_baby_getNumberOfChoice parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSLog(@"responseObject:%@", responseObject);
        if ([responseObject objectForKey:@"response"]) {
            NSArray *dataDictArray = [responseObject objectForKey:@"data"];
            if (dataDictArray.firstObject == nil) {
                
            
            self.selectedStr = @"111111";
            }else
                
            {
                for (NSDictionary *tempdict in dataDictArray) {
                self.selectedStr = [tempdict objectForKey:@"selectednumber"];
            }
            }
            [self assginItemNameArray];
            [self.HealthTableView reloadData];
        }else{
            [MBProgressHUD showError:@"请求数据失败,请检查网络"];
        }
        
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD showError:@"请求数据失败,请检查网络"];
    }];
    
}

- (void)assginItemNameArray
{
        //NSString 转NSData
        NSData *tempData = [self.selectedStr dataUsingEncoding:NSUTF8StringEncoding];
        //NSData 转Byte数组
        Byte *tempByte = (Byte*)[tempData bytes];
        if (tempByte[0] == '1') {
            [self getBodyFatData];
            [self.itemNameArray addObject:@"体重"];
            [self.itemNameArray2 addObject:@"体重"];
            [self.itemNameArray2 addObject:@"BMI指数"];
            [self.itemNameArray2 addObject:@"脂肪率"];
            [self.itemNameArray2 addObject:@"内脏脂肪指数"];
            [self.itemNameArray2 addObject:@"水分率"];
            [self.itemNameArray2 addObject:@"肌肉含量"];
            [self.itemNameArray2 addObject:@"骨含量"];
            [self.itemNameArray2 addObject:@"基础代谢率"];
            _unitArray = @[@"", @"％", @"", @"％", @"kg", @"kg", @"kcal"];
            _tiZhiImageArray = @[@"scale_bmi", @"scale_fat", @"scale_fat2", @"scale_water", @"scale_muscle", @"scale_bones", @"scale_metabolism"];
            
        }
        if (tempByte[1] == '1') {
            [self.itemNameArray addObject:@"体温"];
            [self.itemNameArray2 addObject:@"体温"];
        }
        if (tempByte[2] == '1') {
            [self.itemNameArray addObject:@"血压"];
            [self.itemNameArray2 addObject:@"血压"];
        }
        if (tempByte[3] == '1') {
            [self.itemNameArray addObject:@"血糖"];
            [self.itemNameArray2 addObject:@"血糖"];
        }
        if (tempByte[4] == '1') {
            [self.itemNameArray addObject:@"心率"];
            [self.itemNameArray2 addObject:@"心率"];
        }
        if (tempByte[5] == '1') {
            [self.itemNameArray addObject:@"胎心"];
            [self.itemNameArray2 addObject:@"胎心"];
        }
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    self.itemNameArray = nil;
    self.itemNameArray2 = nil;
    self.itemValueArray2 = nil;
    self.theDayArray = nil;
    self.selectedStr = nil;
    self.calendarDisplayDate = nil;
    _weightFlag = 0;
    _unitArray = nil;
    _tiZhiImageArray = nil;
    [[NSUserDefaults standardUserDefaults]setObject:@"haveChanged" forKey:@"changed"];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [self.HealthTableView reloadData];
    //请求设备管理数据
    [self getHealthNumberOfTests];
    [self getUserParmaterData:[passValue passValue].passValueName username:[passValue passValue].saveDataUserName];
}

- (void)dealloc
{
    if (self.healthCalendar) {
        [self.healthCalendar removeObserver:self forKeyPath:@"date"];
    };
}

@end
